﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Timers;
using System.Windows.Forms;
using _4chanManager.Properties;
using Timer = System.Timers.Timer;

namespace _4chanManager.Logic
{
    public class KeywordMonitor
    {
        private readonly string _webAddress;
        private readonly List<string> _keywords;
        private WebClient _webClient;
        public int minutes = 1;
        public bool containAll;
        private Timer timer;
        private bool isReadingRightNow;

        public event Action ThreadExists;

        public KeywordMonitor(List<string> keywords, string webAddress)
        {
            _keywords = keywords;
            _webAddress = webAddress;
        }

        public void Start()
        {
            timer = new Timer(minutes*60*1000);
            timer.Elapsed += timer_Elapsed;
            timer.Start();
            SearchForThread();
        }

        private void SearchForThread()
        {
            try
            {
                isReadingRightNow = true;
                using (_webClient = new WebClient())
                {
                    _webClient.Headers.Add("user-agent", Helpers.UserAgentHeader);
                    string html = _webClient.DownloadString(_webAddress).ToLower();

                    var treadExists = !containAll
                        ? _keywords.Any(a => html.Contains(a.ToLowerInvariant()))
                        : _keywords.All(a => html.Contains(a.ToLowerInvariant()));

                    if (!treadExists) 
                        return;

                    if (ThreadExists != null)
                        ThreadExists();
                    if (timer != null)
                        timer.Stop();
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(Resources.SomethingWentWrong + e);
                if (timer != null)
                    timer.Stop();
            }
            finally
            {
                isReadingRightNow = false;
            }
        }

        void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            if (!isReadingRightNow)
                SearchForThread();
        }
    }
}
